package org.wattdepot.cli.commands;

import java.util.List;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Provides the summary of a all public sources in the system.
 * 
 * @author Paul Galiza
 * 
 */
public class SourceListCommand implements Command {

  /**
   * Calls the listSources method.
   * 
   * @param userInput The user input.
   * @param client The WattDepotClient
   * @return Returns the list of all the available public sources.
   */
  public String doCommand(List<String> userInput, WattDepotClient client) {
    return listSources(userInput, client);
  }

  /**
   * Creates a table summarizing the public sources in the system, one per line.
   * 
   * @param commandParam The input from user.
   * @param client The WattDepotClient
   * @return Returns a table with all the sources information.
   */
  private String listSources(List<String> commandParam, WattDepotClient client) {
    StringBuffer buff = new StringBuffer();
    String format = "| %1$-15s| %2$15s| %3$-20s\n";
    buff.append(String.format(format, "Name", "Parent", "Description"));

    try {
      List<Source> clientSource = client.getSources();

      for (Source source : clientSource) {
        // checks to see if source is public
        if (source.isPublic()) {
          String sourceName = source.getName();
          String sourceDescription = source.getDescription();
          String sourceParent = "";

          // checks to see if sources have subsources
          if (source.getSubSources() == null) {
            sourceParent = "none";
          }
          else {
            sourceParent = source.getSubSources().getHref().get(0);
          }

          // builds the output string
          buff.append(String.format(format, sourceName, sourceParent, sourceDescription));
        }
      }
    }
    catch (NotAuthorizedException e) {
      e.printStackTrace();
    }
    catch (BadXmlException e) {
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      e.printStackTrace();
    }

    return buff.toString();
  }
}
